package cn.tedu.bece.front.common.response;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

@Data
public class PageObject<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 总记录数 */
    private long total;

    /** 数据列表 */
    private List<T> list;

    public PageObject(long total, List<T> list) {
        this.total = total;
        this.list = list;
    }

    public static <T> PageObject<T> of(List<T> list) {
        if (Objects.isNull(list)) {
            throw new IllegalArgumentException("list不能为空");
        }
        if (list instanceof Page) {
            Page<T> page = (Page<T>) list;
            return new PageObject<>(page.getTotal(), page.getResult());
        }
        return new PageObject<>(list.size(), list);
    }

    public static <T> PageObject<T> page(Integer pageNum, Integer pageSize, PageFunction<T> pf) {
        if (Objects.isNull(pageNum) || pageNum < 1) {
            pageNum = 1;
        }
        if (Objects.isNull(pageSize) || pageSize < 10) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        return PageObject.of(pf.queryPageResult());
    }

    @FunctionalInterface
    public interface PageFunction<T> {
        List<T> queryPageResult();
    }

}
